import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Modal, Space, Form, Input, Button, InputNumber, message, Select} from "antd";
import TheButton from "@/components/TheButton";
import {getShareConfig,apiShareConfigUpdate,apiShareConfigAddList} from "@/request/distribution/awardSetting";
import {MinusCircleOutlined, PlusOutlined} from "@ant-design/icons";
import '../style/style.scss';

class Edit extends Component {
    constructor(props) {
        super(props);
        this.state = {
            openModal: false,
            saveLoading: false,
            flagIndexID: null,
            defaultCommissionRate: null
        }
    }

    componentDidMount() {
        // this.getData()
    }
    openModal = () => {
        this.setState({
            openModal: true
        },()=>{
            this.getData()
        })
    }
    getData = () => {
        getShareConfig().then(res=>{
            if (res.code === 0){
                let d1 = res.data.filter(item=>item.type===1)
                let d2 = res.data.filter(item=>item.type===2)
                this.setState({
                    flagIndexID: res.data.length - 2,
                    defaultCommissionRate: d1[0].commissionRate
                })
                this.formRef.setFieldsValue({
                    list: [...d2,...d1],
                })
            }
        })
    }
    saveCommission = () => {
        this.formRef.validateFields()
            .then(values => {
                let flag = [true];
                let { defaultCommissionRate } = this.state;
                let defaultConfig = values['list'].pop();
                let list = values['list'].map(item=>{
                    // 判断默认区间外与设置条件的分佣比例是否重复
                    if(defaultConfig.commissionRate === item.commissionRate){
                        flag[0] = false
                    }
                    item.type = 2
                    return item
                })
                // 拦截判断默认区间外与设置条件的分佣比例是否重复
                if (flag.includes(false)){
                    message.warning('佣金比例不能重复!')
                    return
                }
                // 拦截默认分佣比例设置与默认考核分佣比例设置是否重复
                if (defaultConfig.commissionRate !== defaultCommissionRate){
                    apiShareConfigUpdate({
                        configId: defaultConfig.configId,
                        commissionRate: defaultConfig.commissionRate,
                        type: 1
                    }).then(res=>{
                        if(res.code !== 0){
                            flag[0] = false
                        }
                    }).catch(errorInfo => {
                        flag[0] = false
                    });
                }
                apiShareConfigAddList({
                    list: list
                }).then(res=>{
                    if (res.code === 0){
                        flag.push(true)
                    }
                    else {
                        flag.push(false)
                    }
                    if (!flag.includes(false)){
                        message.success('保存成功')
                        this.props.update()
                        this.setState({
                            openModal: false
                        })
                    }
                }).catch(errorInfo => {
                    flag.push(false)
                });
            })
            .catch(errorInfo => {
                message.warning('必填项不能为空')
            });
    }

    render() {
        let {openModal, saveLoading, flagIndexID} = this.state
        return (
            <>
                <div style={{textAlign:'center'}}>
                    <TheButton haspermi={['distribution:awardSetting:examine']} type={'default'} size={'middle'} onClick={() => this.openModal()}>编辑</TheButton>
                </div>
                <Modal
                    title="修改条件和比例"
                    visible={openModal}
                    width={1000}
                    okText={"保存"}
                    onOk={this.saveCommission}
                    confirmLoading={saveLoading}
                    destroyOnClose
                    onCancel={() => this.setState({openModal: false})}
                >
                    <Space size={0}>
                        <Space
                            className={'e-th-b-l'}
                        >
                            <span>条件</span>
                        </Space>
                        <Space
                            className={'e-th-b-r'}
                        >
                            <span>佣金比例</span>
                        </Space>
                    </Space>

                    <Form ref={(ref) => this.formRef = ref} >
                        <Form.List name="list">
                            {(fields, {add, remove}) => (
                                <>
                                    <div>
                                        {fields.map(({key, name, ...restField}) => (
                                            <Space key={key} size={0} className={'e-tb-b'}>
                                                <Space
                                                    className={'e-tb-b-l'}
                                                    align="baseline"
                                                >
                                                    {
                                                        key === flagIndexID ? <Form.Item>
                                                                <span>下单人数为区间外的用户数时</span>
                                                            </Form.Item> : <>
                                                            <span>下单用户数</span>
                                                            <Form.Item
                                                                {...restField}
                                                                name={[name, 'min']}
                                                                rules={[
                                                                    {
                                                                        required: true,
                                                                        message: '此项为必填项',
                                                                    },
                                                                ]}
                                                            >
                                                                <InputNumber
                                                                    min={0}
                                                                    max={99999}
                                                                    precision={0}
                                                                    style={{
                                                                        width: 100
                                                                    }}
                                                                />
                                                            </Form.Item>
                                                            <span>~</span>
                                                            <Form.Item
                                                                {...restField}
                                                                name={[name, 'max']}
                                                                rules={[
                                                                    {
                                                                        required: true,
                                                                        message: '此项为必填项',
                                                                    },
                                                                ]}
                                                            >
                                                                <InputNumber
                                                                    min={0}
                                                                    max={99999}
                                                                    precision={0}
                                                                    style={{
                                                                        width: 100
                                                                    }}
                                                                />
                                                            </Form.Item>
                                                            <span>人， 或GMV达到</span>
                                                            <Form.Item
                                                                {...restField}
                                                                name={[name, 'gmv']}
                                                                rules={[
                                                                    {
                                                                        required: true,
                                                                        message: '此项为必填项',
                                                                    },
                                                                ]}
                                                                getValueProps={v => ({value: v?React.$transNum(v, 2, -2):null, v})}
                                                                getValueFromEvent={e => e ? e * 100 : e}
                                                            >
                                                                <InputNumber
                                                                    min={0}
                                                                    max={99999999}
                                                                    precision={0}
                                                                    style={{
                                                                        width: 150
                                                                    }}
                                                                />
                                                            </Form.Item>
                                                            <span>元</span>
                                                        </>
                                                    }
                                                </Space>
                                                <Space
                                                    className={'e-tb-b-r'}
                                                    align="baseline"
                                                >
                                                    <Form.Item
                                                        {...restField}
                                                        name={[name, 'commissionRate']}
                                                        rules={[
                                                            {
                                                                required: true,
                                                                message: '此项为必填项',
                                                            },
                                                        ]}
                                                    >
                                                        <InputNumber
                                                            addonAfter={'%'}
                                                            min={0}
                                                            max={100}
                                                            precision={0}
                                                            style={{
                                                                width: 100
                                                            }}
                                                        />
                                                    </Form.Item>
                                                </Space>
                                                {
                                                    key !== flagIndexID && <MinusCircleOutlined style={{marginLeft: 10}} onClick={() => remove(name)}/>
                                                }
                                            </Space>
                                        ))}
                                    </div>
                                    <Form.Item>
                                        <Button
                                            type="dashed"
                                            onClick={() => {
                                                if (fields.length > 10) {
                                                    message.warning('不能再新增了哦~')
                                                } else {
                                                    add({},fields.length-1)
                                                }
                                            }}
                                            className={'add-btn'}
                                            icon={<PlusOutlined/>}
                                        >
                                            增加
                                        </Button>
                                    </Form.Item>
                                </>
                            )}
                        </Form.List>

                    </Form>
                </Modal>
            </>
        );
    }
}

Edit.propTypes = {};

export default Edit;
